//
//  WinPopup.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 9/7/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "WinPopup.h"
#import "MainGameScene.h"
#import "LevelChoosingScene.h"
#import "DefineText.h"
#import "Utility.h"
#import "UserInfo.h"
#import "SimpleAudioEngine.h"

@implementation WinPopup

-(id) init
{
    if (self = [super initWithColor:ccc4(0, 0, 0, 0)])
    {
        [self initMenu];
        
        self.touchEnabled = YES;
        
        CCFadeTo *fadeTo = [CCFadeTo actionWithDuration:POPUP_ANIMATE_TIME opacity:POPUP_ALPHA];
        [self runAction:fadeTo];
        
        for (int i = 0; i < _children.count; i++)
        {
            CCFadeTo *f = [CCFadeTo actionWithDuration:0.3 opacity:255];
            CCSprite *node = [_children objectAtIndex:i];
            [node setOpacity:0];
            [node runAction:f];
        }
}
    
    return self;
}

-(void) registerWithTouchDispatcher
{
    [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:TOUCH_PRIORITY_RESULT_POPUP swallowsTouches:YES];
}

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    return YES;
}

-(void) initMenu
{
    mMenu = [[CCMenu alloc] init];
    [mMenu setPosition:ccp(0, 0)];
    [self addChild:mMenu];
    
    [mMenu setTouchPriority:TOUCH_PRIORITY_RESULT_POPUP];
    
    
    // create panel
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    CCSprite *panel = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_1];
    [panel setPosition:ccp(winSize.width / 2, winSize.height / 2 + uniPos(50, 100))];
    [panel setColor:CL_PANEL_BG];
    [self addChild:panel];
    
    // create button main menu
    CCSprite *sprMainMenu = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_BTN_1_3];
    CCSprite *sprMainMenuHover = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_BTN_1_3];
    [sprMainMenu setColor:CL_PANEL_BG];
    [sprMainMenuHover setColor:CL_PANEL_BTN];
    CCMenuItem *miMainMenu = [CCMenuItemSprite itemWithNormalSprite:sprMainMenu
                                                     selectedSprite:sprMainMenuHover
                                                             target:self
                                                           selector:@selector(onMainMenu)];
    [miMainMenu setPosition:ccp(winSize.width / 2 - uniPos(94, 188), panel.position.y - uniPos(100.5, 201))];
    [mMenu addChild:miMainMenu];
    
    
    // create button replay
    CCSprite *sprReplay = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_BTN_2_3];
    CCSprite *sprReplayHover = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_BTN_2_3];
    [sprReplay setColor:CL_PANEL_BG];
    [sprReplayHover setColor:CL_PANEL_BTN];
    CCMenuItem *miReplay = [CCMenuItemSprite itemWithNormalSprite:sprReplay
                                                   selectedSprite:sprReplayHover
                                                           target:self
                                                         selector:@selector(onReplay)];
    [miReplay setPosition:ccp(winSize.width / 2, panel.position.y - uniPos(100.5, 201))];
    [mMenu addChild:miReplay];
    
    // create button next
    CCSprite *sprNextLevel = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_BTN_1_3];
    CCSprite *sprNextLevelHover = [CCSprite spriteWithSpriteFrameName:SFN_PANEL_BTN_1_3];
    [sprNextLevel setColor:CL_PANEL_BG];
    [sprNextLevelHover setColor:CL_PANEL_BTN];
    [sprNextLevel setFlipX:YES];
    [sprNextLevelHover setFlipX:YES];
    CCMenuItem *miNextLevel = [CCMenuItemSprite itemWithNormalSprite:sprNextLevel
                                                   selectedSprite:sprNextLevelHover
                                                           target:self
                                                         selector:@selector(onNext)];
    [miNextLevel setPosition:ccp(winSize.width / 2 + uniPos(94, 188), panel.position.y - uniPos(100.5, 201))];
    [mMenu addChild:miNextLevel];
    
    
    // create icon
    CCSprite *iconMenu = [CCSprite spriteWithSpriteFrameName:SFN_ICON_MENU];
    [iconMenu setPosition:miMainMenu.position];
    [self addChild:iconMenu];
    
    CCSprite *iconReplay = [CCSprite spriteWithSpriteFrameName:SFN_ICON_REPLAY];
    [iconReplay setPosition:miReplay.position];
    [self addChild:iconReplay];
    
    CCSprite *iconNext = [CCSprite spriteWithSpriteFrameName:SFN_ICON_NEXT];
    [iconNext setPosition:miNextLevel.position];
    [self addChild:iconNext];
    
    [[LevelManager getInstance] unlockNewLevel];
    [self initStar:3];
    [self initRequire];
    [self animCheck];
}

-(void) onMainMenu
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    [[CCDirector sharedDirector] replaceScene:[LevelChoosingScene scene]];
}

-(void) onReplay
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    [[MainGameScene getInstance] replay];
    [self removeFromParent];
}

-(void) onNext
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    //TODO: need to check if level is max
    [[MainGameScene getInstance] nextLevel];
    [self removeFromParent];
}

-(void) initStar:(int)numStar
{
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    float startX = (winSize.width / 2) - uniPos(50, 100);
    float startY = (winSize.height / 2) + uniPos(100, 200);
    for (int i = 0; i < numStar; i++)
    {
        CCSprite *sprStar = [CCSprite spriteWithSpriteFrameName:SFN_ICON_STAR];
        [sprStar setPosition:ccp(startX, startY)];
        [sprStar setColor:CL_QUATER_WHITE];
        [self addChild:sprStar];
        
        CCSprite *sprStar2 = [CCSprite spriteWithSpriteFrameName:SFN_ICON_STAR];
        [sprStar2 setPosition:ccp(startX, startY)];
        [sprStar2 setVisible:NO];
        [self addChild:sprStar2 z:0 tag:(TAG_STAR + i)];

        
        startX += uniPos(50, 100);
    }
}

-(void) initRequire
{
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    float startX = (winSize.width / 2) - uniPos(100, 200);
    float startY = (winSize.height / 2) + uniPos(50, 100);
    
    NSArray *listRequire = [[LevelManager getInstance] getListLevelRequire];
    for (int i = 0; i < listRequire.count; i++)
    {
        LevelRequire *require = [listRequire objectAtIndex:i];
        CCLabelBMFont *lb = [CCLabelBMFont labelWithString:@"" fntFile:FONT_DEFAULT];
        [lb setString:[self getStringRequire:require]];
        [lb setAnchorPoint:ccp(0, 0.5)];
        [lb setPosition:ccp(startX, startY)];
        [self addChild:lb];
        
        CCSprite *spr = [CCSprite spriteWithSpriteFrameName:SFN_ICON_CHECK];
        [spr setPosition:ccp(startX - uniPos(20, 40), startY)];
        [spr setVisible:NO];
        [self addChild:spr z:0 tag:(TAG_CHECK + i)];
        
        startY -= uniPos(30, 60);
    }
}

-(NSString *) getSoundStar:(int)i
{
    if (i == 0) return SOUND_STAR_1;
    else if (i == 1) return SOUND_STAR_2;
    else if (i == 2) return SOUND_STAR_3;
    
    return nil;
}

-(void) animCheck
{
    NSArray *listRequire = [[LevelManager getInstance] getListLevelRequire];
    NSMutableArray *listSatisfy = [NSMutableArray arrayWithCapacity:listRequire.count];
    
    for (int i = 0; i < listRequire.count; i++)
    {
        LevelRequire *require = [listRequire objectAtIndex:i];
        if (require._type == eLRT_FINISH_PATH)
        {
            [listSatisfy addObject:[NSNumber numberWithBool:YES]];
        }
        else if (require._type == eLRT_RUSH_TIME)
        {
            if ([LevelManager getInstance]._levelTime >= require._value)
                [listSatisfy addObject:[NSNumber numberWithBool:YES]];
            else
                [listSatisfy addObject:[NSNumber numberWithBool:NO]];
        }
        else if (require._type == eLRT_ENERGIZE)
        {
            if ([LevelManager getInstance]._numEnergy >= require._value)
                [listSatisfy addObject:[NSNumber numberWithBool:YES]];
            else
                [listSatisfy addObject:[NSNumber numberWithBool:NO]];
        }
    }
    
    int countStar = 0;
    for (int i = 0; i < listSatisfy.count; i++)
    {
        BOOL isSatisfy = [[listSatisfy objectAtIndex:i] boolValue];
        if (isSatisfy)
        {
            CCSprite *check = (CCSprite *)[self getChildByTag:(TAG_CHECK + i)];
            [check setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:SFN_ICON_CHECK]];
            
            // for action
            CCDelayTime *delay = [CCDelayTime actionWithDuration:(1 + i)];
            CCCallBlock *callBlock = [CCCallBlock actionWithBlock:^{
                [check setVisible:YES];
                [check setOpacity:0];
            }];
            CCFadeTo *fadeTo = [CCFadeTo actionWithDuration:0.5f opacity:255];
            CCSequence *sequence = [CCSequence actions:delay, callBlock, fadeTo, nil];
            [check runAction:sequence];
            
            // for star
            int numStarCount = 1;
            if (listRequire.count == 1)
                numStarCount = 3;
            for (int j = 0; j < numStarCount; j++)
            {
                CCSprite *star = (CCSprite *)[self getChildByTag:(TAG_STAR + countStar)];
                CCDelayTime *delay2 = [CCDelayTime actionWithDuration:(1 + i)];
                CCCallBlock *callBlock2 = [CCCallBlock actionWithBlock:^{
                    [star setVisible:YES];
                    [star setScale:0];
                    [[Utility getInstance] playEffect:[self getSoundStar:(i + j)]];
                }];
                CCScaleTo *scaleTo2 = [CCScaleTo actionWithDuration:0.5f scale:1.0f];
                CCRotateBy *rotateBy2 = [CCRotateBy actionWithDuration:0.5f angle:360];
                CCSpawn *spawn2 = [CCSpawn actionOne:scaleTo2 two:rotateBy2];
                CCSequence *sequence2 = [CCSequence actions:delay2, callBlock2, spawn2, nil];
                [star runAction:sequence2];
                countStar++;
            }
        }
        else
        {
            CCSprite *check = (CCSprite *)[self getChildByTag:(TAG_CHECK + i)];
            [check setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:SFN_ICON_CANCEL]];
            
            CCDelayTime *delay = [CCDelayTime actionWithDuration:(1 + i)];
            CCCallBlock *callBlock = [CCCallBlock actionWithBlock:^{
                [check setVisible:YES];
                [check setColor:CL_BTN_INFO];
                [check setOpacity:0];
            }];
            CCFadeTo *fadeTo = [CCFadeTo actionWithDuration:0.5f opacity:255];
            CCSequence *sequence = [CCSequence actions:delay, callBlock, fadeTo, nil];
            [check runAction:sequence];
        }
    }
    
    LevelDetail *levelDetail = [[LevelManager getInstance] getCurrentLevelDetail];
    

    if (countStar > levelDetail._star)
    {
        // add gold
        CCLOG(@"add gold");
        int numGold = (countStar - levelDetail._star) * GOLD_PER_STAR;
        [UserInfo getInstance]._userGold += numGold;
        [[UserInfo getInstance] saveUserInfo];
        
        CGSize winSize = [[CCDirector sharedDirector] winSize];
        CCLabelBMFont *lb = [CCLabelBMFont labelWithString:@"" fntFile:FONT_NUMBER];
        [lb setString:[NSString stringWithFormat:@"+%d", numGold]];
        [lb setAnchorPoint:ccp(0, 0.5)];
        [lb setPosition:ccp(winSize.width / 2 + uniPos(75, 150), winSize.height / 2 + uniPos(100, 200))];
        [lb setVisible:NO];
        [self addChild:lb];
        
        CCDelayTime *d1 = [CCDelayTime actionWithDuration:(listRequire.count + 0.5)];
        CCCallBlock *c1 = [CCCallBlock actionWithBlock:^{
            [lb setVisible:YES];
            [lb setOpacity:0];
        }];
        CCFadeTo *f1 = [CCFadeTo actionWithDuration:0.2 opacity:255];
        CCSequence *s1 = [CCSequence actions:d1, c1, f1, nil];
        [lb runAction:s1];
        
        CCSprite *sprGold = [CCSprite spriteWithSpriteFrameName:SFN_ICON_GOLD];
        [sprGold setPosition:ccp(lb.position.x + lb.contentSize.width + uniPos(15, 30), lb.position.y + uniPos(2, 4))];
        [sprGold setVisible:NO];
        [self addChild:sprGold];
        
        CCDelayTime *d2 = [CCDelayTime actionWithDuration:(listRequire.count + 0.5)];
        CCCallBlock *c2 = [CCCallBlock actionWithBlock:^{
            [sprGold setVisible:YES];
            [sprGold setOpacity:0];
        }];
        CCFadeTo *f2 = [CCFadeTo actionWithDuration:0.2 opacity:255];
        CCSequence *s2 = [CCSequence actions:d2, c2, f2, nil];
        [sprGold runAction:s2];
    }
    
    // save data
    levelDetail._time = [LevelManager getInstance]._levelTime;
    levelDetail._energy = [LevelManager getInstance]._numEnergy;
    if (countStar > levelDetail._star)
        levelDetail._star = countStar;
    
    [[Utility getInstance] saveObject:levelDetail forKey:[[LevelManager getInstance] getCurrentLevelName]];
}

-(NSString *) getStringRequire:(LevelRequire *)require
{
    NSString *str;
    if (require._type == eLRT_FINISH_PATH)
    {
        str = [NSString stringWithFormat:@"%@", TEXT_LEVEL_REQUIRE_FINISH_PATH];
        return str;
    }
    else if (require._type == eLRT_RUSH_TIME)
    {
        if (require._value > 1)
            str = [NSString stringWithFormat:TEXT_LEVEL_REQUIRE_RUSH_TIMES, require._value];
        else
            str = [NSString stringWithFormat:TEXT_LEVEL_REQUIRE_RUSH_TIME, require._value];
        return str;
    }
    else if (require._type == eLRT_ENERGIZE)
    {
        if (require._value > 1)
            str = [NSString stringWithFormat:TEXT_LEVEL_REQUIRE_ENERGIZES, require._value];
        else
            str = [NSString stringWithFormat:TEXT_LEVEL_REQUIRE_ENERGIZE, require._value];
        return str;
    }
    
    return nil;
}

-(void) dealloc
{
    CCLOG(@"Win popup dealloc!");
    [mMenu release];
    [super dealloc];
}

@end


